using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class NPCBase : MonoBehaviour, IInteractive
{
    [Header("----- Tip Float -----")]
    [SerializeField] protected Transform _interactToolTip;
    [SerializeField] protected float _floatRange = 1;
    [SerializeField] protected float _floatSpeed = .2f;

    protected Vector2 _originalTipPos;
    private SpriteRenderer _interactTipSr;
    private TextMeshPro _interactTmp;
    private Coroutine _fadeCoroutine;
    private bool _isEnterInteractArea;
    private void Awake()
    {
        _originalTipPos = _interactToolTip.position;
        _interactTipSr = _interactToolTip.GetComponent<SpriteRenderer>();
        _interactTmp = _interactToolTip.GetComponentInChildren<TextMeshPro>();

        _interactToolTip.gameObject.SetActive(false);
    }
    private void OnDestroy()
    {
        StopAllCoroutines();
    }
    protected virtual void Update()
    {
        HandleTipFloat();
    }

    private void HandleTipFloat()
    {
        if (_interactToolTip.gameObject.activeSelf == false)
            return;

        float floatOffset = Mathf.Sin(Time.time * _floatSpeed) * _floatRange;

        _interactToolTip.position = _originalTipPos + new Vector2(0f, floatOffset);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player") == false)
            return;

        _interactToolTip.gameObject.SetActive(true);

        StartInteractTipFade(.2f, 0, 1);
        _isEnterInteractArea = true;
    }
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player") == false)
            return;

        StartInteractTipFade(.2f, 1, 0);
        _isEnterInteractArea = false;
    }
    
    private void StartInteractTipFade(float duration, float startFade, float endFade)
    {
        if (_fadeCoroutine != null)
            StopCoroutine(_fadeCoroutine);

        _fadeCoroutine = StartCoroutine(InteractTipFadeCo(duration, startFade, endFade));
    }

    private IEnumerator InteractTipFadeCo(float duration,float startFade, float endFade)
    {
        float timer = 0;
        float startApalh = startFade;

        Color fadeColor = _interactTipSr.color;
        Color tmpFadeColor = _interactTmp.color;
        while (timer < duration)
        {
            timer += Time.deltaTime;

            float fadeApalh = Mathf.Lerp(startApalh, endFade, timer / duration);

            fadeApalh = Mathf.Clamp01(fadeApalh);

            fadeColor.a = fadeApalh;
            tmpFadeColor.a = fadeApalh;
            _interactTipSr.color = fadeColor;
            _interactTmp.color = tmpFadeColor;

            yield return null;
        }
    }
    protected virtual void Start(){ }
    public virtual void Interact()
    {
        if (_isEnterInteractArea == false)
            return;

        StartInteractTipFade(.2f, 1, 0);
    }
}
